const gulp = require('gulp') //创建
const uglify = require('gulp-uglify') //压缩
const babel = require('gulp-babel'); //es6转es5
const rev = require('gulp-rev') //加随机名
const clean = require('gulp-clean') //删除文件目录
const minifyCss = require('gulp-minify-css') //压缩js
const imagemin = require('gulp-imagemin') //压缩图片
const minifyhtml = require('gulp-minify-html') //压缩html
const revCollector = require('gulp-rev-collector') //根据temp目录记录的规则 替换html路径




// 清除
const fs = require('fs')
gulp.task('clean', over => {
    if (fs.existsSync('dist/')) {
        gulp.src('dist/', { read: false })
            .pipe(clean());
    }
    setTimeout(() => {
        over()
    }, 2000)
})


// html
gulp.task('html', over => {
    gulp
        .src(['temp/**/*.json', './src/*.html'])
        .pipe(revCollector())
        .pipe(minifyhtml())
        .pipe(gulp.dest('./dist/'))
    over()
})

// js
gulp.task('js', over => {
    gulp
        .src('./src/js/*.js')
        .pipe(babel({ "presets": ["env"] }))
        .pipe(uglify())
        .pipe(rev())
        .pipe(gulp.dest('./dist/js/'))

    // 打包将js对应的随机名保存到json中
    .pipe(rev.manifest())
        .pipe(gulp.dest('temp/js'))

    over()

})

// css
gulp.task('css', over => {
    gulp
        .src('./src/css/*.css')
        .pipe(minifyCss())
        .pipe(rev())
        .pipe(gulp.dest('./dist/css/'))
        // 打包将css对应的随机名保存到json中
        .pipe(rev.manifest())
        .pipe(gulp.dest('temp/css'))
    over()

})

// 打包img
gulp.task('imgs', () => {
    gulp
        .src('./src/imgs/*.*')
        .pipe(imagemin())
        .pipe(gulp.dest('./dist/imgs/'))
    setTimeout(() => {
        over()
    }, 30000)
})

// 批量打包

gulp.task('build', gulp.series('clean', 'js', 'css', 'imgs', 'html', () => {
    console.log('build打包完成');
}))

//通过node搞服务器，开发的时候用

const server = require('browser-sync').create();
const watch = require('gulp-watch');
const { createProxyMiddleware } = require('http-proxy-middleware');
gulp.task('serve', function() {
    server.init({
        // server:'./src',  // 留心：后期访问文件的时候 加上 html/xxx.html
        server: {
            baseDir: './src',
            middleware: [
                createProxyMiddleware('/api', {
                    target: 'http://kg.zhaodashen.cn/v1/',
                    changeOrigin: true,
                }),
                // ...
            ]
        },
        port: 3000
    })

    watch('./src/html/*', function() {
        console.log('html change')
        server.reload()
    })

    watch('./src/style/*', function() {
        console.log('style change')
        server.reload()
    })

    watch('./src/js/*', function() {
        console.log('js change')
        server.reload()
    })
})